package main

import (
	"fmt"
	"reflect"
)

type User struct {
	Id   int
	Name string
	Age  int
}

func (this User) String() {
	println("User: ", this.Id, this.Name, this.Age)
}

func Info(o interface{}) {
	v := reflect.ValueOf(o) //获取 Value 信息

	t := v.Type() //通过 value 获取 Type

	println("Type:", t.Name()) //类型名称

	//访问接口字段名、字段类型、字段信息值信息
	println("Field:")
	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)             //通过索引获取 struct 字段
		value := v.Field(i).Interface() //"Interface()" 方法将所选字段的值作为空接口类型返回，然后可以进一步断言为具体类型

		//类型查询
		switch value := value.(type) {
		case int:
			fmt.Printf("%6s: %v = %d\n", field.Name, field.Type, value) //    Id: int = 1
		case string:
			fmt.Printf("%6s: %v = %s\n", field.Name, field.Type, value) //  Name: string = 喜羊羊
		default:
			fmt.Printf("%6s: %v = %s\n", field.Name, field.Type, value) //   Age: int = 18
		}
	}
}

func main() {
	u := User{Id: 1, Name: "喜羊羊", Age: 18}
	Info(u)
}
